# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: fengyang

import datetime
import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def week_expiration(trading_datetime):
  date = trading_datetime.date()
  if date.weekday() < 4:
    expiry_date = date + datetime.timedelta(days=(4 - date.weekday()))
  elif date.weekday() > 4:
    expiry_date = date + datetime.timedelta(days=(4 - date.weekday() + 7))
  elif trading_datetime.hour < 8:
    expiry_date = date
  elif trading_datetime.hour >= 8:
    expiry_date = date + datetime.timedelta(days=7)

  return datetime.datetime(
      year=expiry_date.year,
      month=expiry_date.month,
      day=expiry_date.day,
      hour=8)


def next_week_expiration(trading_datetime):
  return week_expiration(week_expiration(trading_datetime) + datetime.timedelta(days=1))


def last_friday_of_month(year, month):
  if month == 12:
    next_month = datetime.datetime(
        year=year + 1,
        month=1,
        day=1,
        hour=8)
  else:
    next_month = datetime.datetime(
        year=year,
        month=month + 1,
        day=1,
        hour=8)
  this_month_last_day = next_month - datetime.timedelta(days=1)
  day = this_month_last_day
  while True:
    if day.weekday() == 4:
      break
    day = day - datetime.timedelta(days=1)
  return day


def quarter_expiration(trading_datetime):
  quarter_month = ((trading_datetime.month // 4 + 1) % 5) * 3
  this_quater_friday = last_friday_of_month(trading_datetime.year, quarter_month)
  if (trading_datetime > this_quater_friday):
    if quarter_month == 12:
      return last_friday_of_month(trading_datetime.year + 1, 3)
    else:
      return last_friday_of_month(trading_datetime.year, quarter_month + 3)
  else:
    return this_quater_friday


def next_quarter_expiration(trading_datetime):
  return quarter_expiration(quarter_expiration(trading_datetime) + datetime.timedelta(days=1))


def nnext_quarter_expiration(trading_datetime):
  return quarter_expiration(next_quarter_expiration(trading_datetime) + datetime.timedelta(days=1))


def nnnext_quarter_expiration(trading_datetime):
  return quarter_expiration(nnext_quarter_expiration(trading_datetime) + datetime.timedelta(days=1))


def month_expiration(trading_datetime):
  friday = last_friday_of_month(trading_datetime.year, trading_datetime.month)
  if (trading_datetime > friday):
    if trading_datetime.month == 12:
      return last_friday_of_month(trading_datetime.year + 1, 1)
    else:
      return last_friday_of_month(trading_datetime.year, trading_datetime.month + 1)
  else:
    return friday

def next_month_expiration(trading_datetime):
  return month_expiration(month_expiration(trading_datetime) + datetime.timedelta(days=1))

def to_expire(info, expire_to_norm):
  period = info["settlement_period"]

  if period == "perpetual":
    return "PERPETUAL"

  expiration = datetime.datetime.fromtimestamp(info["expiration_timestamp"] / 1000)
  for item in expire_to_norm:
    if expiration == item:
      expiration = item
      break
  return expire_to_norm[expiration]


def generate():
  mea = 'Futures.Deribit.v2'
  me = 'Futures.Deribit'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  currencies_data = (requests.get("https://www.deribit.com/api/v2/public/get_currencies")
                     .json())["result"]
  currencies = []
  for info in currencies_data:
    currencies.append(info["currency"])

  data = []
  for currency in currencies:
    url = "https://www.deribit.com/api/v2/public/get_instruments?currency={}".format(currency)
    response = requests.get(url).json()
    data.extend(response['result'])
    now = datetime.datetime.fromtimestamp(response['usOut'] / 1000000)

  week = week_expiration(now)
  next_week = next_week_expiration(now)
  month = month_expiration(now)
  next_month = next_month_expiration(now)
  quarter = quarter_expiration(now)
  next_quarter = next_quarter_expiration(now)
  nnext_quarter = nnext_quarter_expiration(now)
  nnnext_quarter = nnnext_quarter_expiration(now)

  expire_to_norm = {
      week: "WEEK",
      next_week: "NEXT_WEEK",
      month: "MONTH",
      next_month: "NEXT_MONTH",
      quarter: "QUARTER",
      next_quarter: "NEXT_QUARTER",
      nnext_quarter: "NNEXT_QUARTER",
      nnnext_quarter: "NNNEXT_QUARTER",
  }

  pis = []
  for info in data:
    native_symbol = info['instrument_name']
    native_base = info['base_currency']
    native_quote = info['quote_currency']

    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    # only supports future
    if info['kind'] != "future":
      continue
    if not info['is_active']:
      continue

    is_inverse = info["instrument_type"] == "reversed"
    try:
      contract_type = to_expire(info, expire_to_norm)
    except KeyError as e:
      print("[%s] ignore symbol: %s, expiry_date: %s" % (mea, native_symbol, e))
      continue
    symbol = "%s-%s.%s" % (base, quote, contract_type)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=info["tick_size"],
        qty_ticksize=info["contract_size"], # please let OG team know if this field is changed as
                                            # FIX client requires this field
        contract_value=float(1), # deribit accept order qty in USD unit
        is_inverse=is_inverse,
        min_qty=info["min_trade_amount"],
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
